package com.liang.blog.controller;

import com.github.houbb.heaven.util.lang.StringUtil;
import com.github.houbb.sensitive.word.core.SensitiveWordHelper;
import com.liang.blog.enmus.ResultCodeEnum;
import com.liang.blog.mapper.BlogInfoMapper;
import com.liang.blog.model.BlogInfo;
import com.liang.blog.model.Result;
import com.liang.blog.model.UserInfo;
import com.liang.blog.service.BlogService;
import com.liang.blog.utils.JwtUtils;
import io.jsonwebtoken.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Slf4j
@RequestMapping("/blog")
@RestController
public class BlogController {
    @Autowired
    private BlogService blogService;
    @RequestMapping("/getList")
    public List<BlogInfo> getList() {
       return blogService.getList();
    }
    @RequestMapping("/getBlogDetail")
    public BlogInfo getBlogDetail(Integer blogId, HttpServletRequest request) {
            log.info("getBlogDetail 接收参数:blogId: " +blogId);
       Assert.notNull(blogId,"blogId不能为null");
       BlogInfo blogInfo = blogService.getBlogDetail(blogId);
       //作者ID
        Integer authorId = blogInfo.getUserId();
        //登录用户ID
        String userToken = request.getHeader("user_token_header");
        Integer userId = JwtUtils.getUserIdFromToken(userToken);
        if(authorId!=null && authorId==userId) {
            blogInfo.setLoginUser(true);
        }
        return blogInfo;
    }
    /**
     * 发布博客
     */
//    @RequestMapping("/add")
//    public Boolean addBlog(@Validated @RequestBody BlogInfo blogInfo ,HttpServletRequest request) { //json需要用@RequestBody接收
//        System.out.println(" blogInfo:" + blogInfo);
//       log.info("addBlog 接收参数 ：" + blogInfo);
//        //获取userId
//        String userToken = request.getHeader("user_token_header");
//        Integer userId = JwtUtils.getUserIdFromToken(userToken);
//        Assert.notNull(userId,"用户未登录");//大概率不会为null,可以去掉
//        blogInfo.setUserId(userId);
//        Integer result = null;
//       try{
////           if (!StringUtil.isEmpty(SensitiveWordHelper.findFirst(title)) || !StringUtil.isEmpty(SensitiveWordHelper.findFirst(content))){
////
////               //打印日志
////               log.warn(ResultCode.FAILED_ARTICLE_CONTENT_BANNED.toString());
////               //返回响应
////               return AppResult.failed(ResultCode.FAILED_ARTICLE_CONTENT_BANNED);
////           }
//           result = blogService.insertBlog(blogInfo);
//           if(result == 1) {
//               return true;
//           }
//       }catch (Exception e) {
//           log.error("发布博客失败，e: " +e);
//       }
//        return false;
//    }
    @RequestMapping("/add")
    public Result addBlog(String kind, String title, String content, HttpServletRequest request) {
        String userToken = request.getHeader("user_token_header");
        Integer userId = JwtUtils.getUserIdFromToken(userToken);
        System.out.println("userToken:"+ userToken);
        System.out.println("参数:"+title+"and" +content + "and" +kind);
        Assert.notNull(userId, "用户未登录");


        try {
            // 检测标题或内容是否包含敏感词
            String sensitiveWordInTitle = SensitiveWordHelper.findFirst(title);
            String sensitiveWordInContent = SensitiveWordHelper.findFirst(content);
            if (!StringUtil.isEmpty(sensitiveWordInTitle) || !StringUtil.isEmpty(sensitiveWordInContent)) {
                // 记录敏感词信息
                log.warn("检测到敏感词，标题中的敏感词：{}，内容中的敏感词：{}", sensitiveWordInTitle, sensitiveWordInContent);
                // 直接返回错误 Result
                return Result.fail(ResultCodeEnum.WORLD_BANNED.getCode(), "内容不合法");

           }
            BlogInfo blogInfo = new BlogInfo();
            blogInfo.setUserId(userId);
            blogInfo.setTitle(title);
            blogInfo.setContent(content);
            blogInfo.setKind(kind);
        Integer result = blogService.insertBlog(blogInfo);
           if(result == 1) {
               return Result.success("发布成功");
           }
       }catch (Exception e) {
           log.error("发布博客失败，e: " +e);
       }
        return Result.fail("发布失败");

        }

/**
 * 更新博客
 */
   @RequestMapping("/updateBlog")
   public Boolean updateBlog(@Validated @RequestBody BlogInfo blogInfo) {
       log.info("updateBlog 接收参数：" + blogInfo);
       Integer result =  null;
      try {
          result = blogService.update(blogInfo);
          if(result <= 0) {
              return false;
          }
      }catch (Exception e) {
          log.error("updateBlog 发生异常，e:  ",e);
      }
      return true;
   }

   @RequestMapping("/deleteBlog")
   public Boolean deleteBlog(Integer blogId) {
       Assert.notNull(blogId,"删除的博客ID不能为null");
       log.info("deleteBlog 接收参数：" + blogId);
       Integer result =  null;
       try {
           BlogInfo blogInfo = new BlogInfo();
           blogInfo.setId(blogId);
           blogInfo.setDeleteFlag(1);
           result = blogService.update(blogInfo);
           if(result <= 0) {
               return false;
           }
       }catch (Exception e) {
           log.error("deleteBlog 发生异常，e:  ",e);
       }
       return true;
   }
   @GetMapping("/findCountById")
    public Long findCountById(HttpServletRequest request) {
       String userToken = request.getHeader("user_token_header");
       Integer id = JwtUtils.getUserIdFromToken(userToken);
       Assert.notNull(id,"用户未登录");
        return blogService.selectCountById(id);
   }
   @GetMapping("/selectKindById")
    public Long selectKindById(HttpServletRequest request){
       String userToken = request.getHeader("user_token_header");
       Integer id = JwtUtils.getUserIdFromToken(userToken);
       Assert.notNull(id,"用户未登录");
       return blogService.selectKindById(id);
   }
    @GetMapping("/selectByTitleKey")
    public List<BlogInfo> selectByTitleKey(String titleKey) {
        System.out.println("搜索");
       return blogService.selectByTitleKey(titleKey);
    }
}
